import { ref, nextTick } from 'vue'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useModalStore } from '@/stores/modalStore'
export default function () {
  // 资源数组
  const imgsList = ref<string[]>([])

  // 拖拽
  const dropElement = ref<HTMLElement | null>(null)
  async function dragEnter() {
    dropElement.value?.classList.add('dragover')
    await nextTick()
  }
  async function dragLeave() {
    dropElement.value?.classList.remove('dragover')
    await nextTick()
  }
  async function drop(e: DragEvent) {
    dropElement.value?.classList.remove('dragover')
    // input 添加文件
    if (e.target !== null) {
      const files = (e.dataTransfer as DataTransfer).files as FileList
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          const url = reader.result as string
          imgsList.value.push(url)
        }
      }
    }
  }

  const input = ref<HTMLInputElement | null>(null)
  function clickInput() {
    if (input.value) {
      input.value.click()
    }
  }
  async function selectFiles(e: InputEvent) {
    const input = e.target as HTMLInputElement
    const files = input.files as FileList
    // 获取图像链接
    const { postImgToUrl } = useAsyncAxios()
    const { status, data } = await postImgToUrl(files)
    console.log(data)

    if (status === 200) {
      for (let i = 0; i < data.length; i++) {
        const url = data[i]
        imgsList.value.push(url)
      }
    } else {
      const { changeData } = useModalStore()
      changeData({ status, data })
    }
  }

  function copyUrl(index: number) {
    const blobUrl = imgsList.value[index]
    navigator.clipboard.writeText(blobUrl)
  }
  function removeImg(index: number) {
    imgsList.value.splice(index, 1)
  }
  return {
    input,
    dropElement,
    imgsList,
    dragEnter,
    dragLeave,
    drop,
    clickInput,
    selectFiles,
    copyUrl,
    removeImg
  }
}
